package ltd.hxya.novel.user.interceptor;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import ltd.hxya.novel.common.bean.Result;
import ltd.hxya.novel.common.bean.UserBean;
import ltd.hxya.novel.common.constant.JwtConstant;
import ltd.hxya.novel.common.utils.JwtUtils;
import ltd.hxya.novel.common.bean.ResultEnum;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


/**
 * 登录拦截器，拦截未登录的请求
 */
public class UserLoginInterceptor implements HandlerInterceptor {

    public static final ThreadLocal<UserBean> threadLocal = new ThreadLocal<>();


    /**
     * 目标方法执行之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String token = request.getHeader(JwtConstant.TOKEN_HEADER_KEY);
//        //从JWT中取出数据，并验证token
//        if (StringUtils.isEmpty(token) || token.equals("")){
//            response.setContentType("application/json;charset=utf-8");
//            PrintWriter writer = response.getWriter();
//            Result<Void> result = Result.fail(ResultEnum.NOT_LOGIN.getCode(), ResultEnum.NOT_LOGIN.getMsg());
//            String json = JSON.toJSONString(result);
//            writer.print(json);
//            return false;
//        }
//        String json = JwtUtils.checkToken(token);
//        UserBean userBean = JSON.parseObject(json, new TypeReference<UserBean>() {
//        });
//        threadLocal.set(userBean);
//        return true;
//    }
}
